import axios from 'axios';
import app from "@vue/main"; //引入vue实例
//axios封装
let http = axios.create({
  //headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  timeout: 20000, //延时
});
http.defaults.headers.post['Content-Type'] = "application/x-www-form-urlencoded";
http.defaults.headers.get['Content-Type'] = 'application/json; charset=utf-8';
http.interceptors.request.use( //请求参数设置
  config => {
    //token添加
    var userInfo = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : {};//直接读取存储方式vuex异步存在bug
    userInfo?.token && (config.headers["token"] = userInfo.token);
    if (config.method == "post" && !config.data) {
      config.data = config.params || {};
      config.params = undefined;
      userInfo?.userId && (config.data.userId = userInfo.userId);
    } else if (config.method == "get" && !config.params) {
      config.params = config.data || {};
      config.data = undefined;
      userInfo?.userId && (config.params.userId = userInfo.userId);
    };
    return config;
  },
  err => {
    console.log(err)
    return Promise.reject(err)
  })
http.interceptors.response.use( //响应请求
  config => {
    if (config.data.Code === 200) { //成功
      return config
    } else if (config.data.Code === 403) { //登录失效
      app.$alert(config.data.msg).then(_ => { 
        app.$store.commit("userInfo", {});//清空登录信息
        app.$router.push({
          name: "login"
        })
      });
    } else if (config.data.Code === 500) { //失败
      app.$toast(config.data.msg, {
        durtaion: 200,
        location: 'center',
      });
      return Promise.reject('error')
    } else if (config.data.Code === 401) { //系统繁忙
      app.$toast(config.data.msg, {
        durtaion: 200,
        location: 'center',
      });
      return Promise.reject('error')
    } else {
      return Promise.reject('error')
    }
  },
  err => {
    console.log(err);
    return Promise.reject(err)
  })

export default http
